package com.sugar.real.estate.module.business.service.dicttype;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sugar.real.estate.framework.common.pojo.PageParam;
import com.sugar.real.estate.framework.common.pojo.PageResult;
import com.sugar.real.estate.framework.common.util.object.BeanUtils;
import com.sugar.real.estate.module.business.controller.admin.dicttype.vo.BizDictDataSimpleRespVO;
import com.sugar.real.estate.module.business.controller.admin.dicttype.vo.BizDictTypePageReqVO;
import com.sugar.real.estate.module.business.controller.admin.dicttype.vo.BizDictTypeSaveReqVO;
import com.sugar.real.estate.module.business.dal.dataobject.dicttype.BizDictDataDO;
import com.sugar.real.estate.module.business.dal.dataobject.dicttype.BizDictTypeDO;
import com.sugar.real.estate.module.business.dal.mysql.dicttype.BizDictDataMapper;
import com.sugar.real.estate.module.business.dal.mysql.dicttype.BizDictTypeMapper;
import com.sugar.real.estate.module.business.util.I18nUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.sugar.real.estate.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.sugar.real.estate.module.business.enums.ErrorCodeConstants.BIZ_DICT_DATA_IS_EXISTS;
import static com.sugar.real.estate.module.business.enums.ErrorCodeConstants.BIZ_DICT_DATA_NOT_EXISTS;

/**
 * 字典类型 Service 实现类
 *
 * @author Ysugar
 */
@Service
@Validated
public class BizDictTypeServiceImpl implements BizDictTypeService {

    @Resource
    private BizDictTypeMapper bizDictTypeMapper;
    @Resource
    private BizDictDataMapper bizDictDataMapper;

    @Override
    public Long createBizDictType(BizDictTypeSaveReqVO createReqVO) {
        // 插入
        BizDictTypeDO bizDictType = BeanUtils.toBean(createReqVO, BizDictTypeDO.class);
        bizDictTypeMapper.insert(bizDictType);
        // 返回
        return bizDictType.getId();
    }

    @Override
    public void updateBizDictType(BizDictTypeSaveReqVO updateReqVO) {
        // 校验存在
        validateBizDictTypeExists(updateReqVO.getId());
        // 更新
        BizDictTypeDO updateObj = BeanUtils.toBean(updateReqVO, BizDictTypeDO.class);
        bizDictTypeMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBizDictType(Long id) {
        // 校验存在
        validateBizDictTypeExists(id);
        // 删除
        bizDictTypeMapper.deleteById(id);

        // 删除子表
        deleteBizDictDataByDictTypeId(id);
    }

    @Override
        @Transactional(rollbackFor = Exception.class)
    public void deleteBizDictTypeListByIds(List<Long> ids) {
        // 校验存在
        validateBizDictTypeExists(ids);
        // 删除
        bizDictTypeMapper.deleteByIds(ids);
    
    // 删除子表
            deleteBizDictDataByDictTypeIds(ids);
    }

    private void validateBizDictTypeExists(List<Long> ids) {
        List<BizDictTypeDO> list = bizDictTypeMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
        }
    }

    private void validateBizDictTypeExists(Long id) {
        if (bizDictTypeMapper.selectById(id) == null) {
        }
    }

    @Override
    public BizDictTypeDO getBizDictType(Long id) {
        return bizDictTypeMapper.selectById(id);
    }

    @Override
    public PageResult<BizDictTypeDO> getBizDictTypePage(BizDictTypePageReqVO pageReqVO) {
        return bizDictTypeMapper.selectPage(pageReqVO);
    }

    // ==================== 子表（字典数据） ====================

    @Override
    public PageResult<BizDictDataDO> getBizDictDataPage(PageParam pageReqVO, Long dictTypeId) {
        return bizDictDataMapper.selectPage(pageReqVO, dictTypeId);
    }

    @Override
    public Long createBizDictData(BizDictDataDO bizDictData) {
        if (bizDictDataMapper.selectCount(Wrappers.<BizDictDataDO>lambdaQuery()
                .eq(BizDictDataDO::getDictTypeId, bizDictData.getDictTypeId()).eq(BizDictDataDO::getValue, bizDictData.getValue())) > 0)
            throw exception(BIZ_DICT_DATA_IS_EXISTS);

        bizDictDataMapper.insert(bizDictData);
        return bizDictData.getId();
    }

    @Override
    public void updateBizDictData(BizDictDataDO bizDictData) {
        // 校验存在
        validateBizDictDataExists(bizDictData.getId());

        if (bizDictDataMapper.selectCount(Wrappers.<BizDictDataDO>lambdaQuery()
                .eq(BizDictDataDO::getDictTypeId, bizDictData.getDictTypeId())
                .eq(BizDictDataDO::getValue, bizDictData.getValue())
                .ne(BizDictDataDO::getId, bizDictData.getId())) > 0)
            throw exception(BIZ_DICT_DATA_IS_EXISTS);

        // 更新
        bizDictData.clean(); // 解决更新情况下：updateTime 不更新
        bizDictDataMapper.updateById(bizDictData);
    }

    @Override
    public void deleteBizDictData(Long id) {
        // 删除
        bizDictDataMapper.deleteById(id);
    }

	@Override
	public void deleteBizDictDataListByIds(List<Long> ids) {
        // 删除
        bizDictDataMapper.deleteByIds(ids);
	}

    @Override
    public BizDictDataDO getBizDictData(Long id) {
        return bizDictDataMapper.selectById(id);
    }

    @Override
    public List<BizDictDataSimpleRespVO> getAllDictDataByTypeId(Long typeId) {
        return BeanUtils.toBean(bizDictDataMapper.selectList(Wrappers.<BizDictDataDO>lambdaQuery()
                .eq(BizDictDataDO::getDictTypeId, typeId).orderByDesc(BizDictDataDO::getSort)), BizDictDataSimpleRespVO.class,
                o -> o.setLabel(o.getLabelZhCn() + " (" + o.getLabelEnUs() + ")"));
    }

    @Override
    public List<BizDictDataSimpleRespVO> appGetAllDictDataByTypeId(Long typeId) {
        return BeanUtils.toBean(bizDictDataMapper.selectList(Wrappers.<BizDictDataDO>lambdaQuery()
                        .eq(BizDictDataDO::getDictTypeId, typeId).orderByDesc(BizDictDataDO::getSort)), BizDictDataSimpleRespVO.class,
                o -> o.setLabel(I18nUtil.getMessage(o, "getLabel")));
    }

    @Override
    public Map<String, List<BizDictDataSimpleRespVO>> appGetAllDictDataAll() {
        List<BizDictDataSimpleRespVO> respVO = BeanUtils.toBean(bizDictDataMapper.selectList(Wrappers.<BizDictDataDO>lambdaQuery().orderByDesc(BizDictDataDO::getSort)), BizDictDataSimpleRespVO.class,
                o -> o.setLabel(I18nUtil.getMessage(o, "getLabel")));

        return respVO.stream().collect(Collectors.groupingBy(o -> "type" + o.getDictTypeId()));
    }

    @Override
    public String appGetAllDictDataLabel(Long typeId, String value) {
        BizDictDataDO bizDictDataDO = bizDictDataMapper.selectOne(Wrappers.<BizDictDataDO>lambdaQuery()
                .eq(BizDictDataDO::getDictTypeId, typeId)
                .eq(BizDictDataDO::getValue, value));
        if (Objects.nonNull(bizDictDataDO)) {
            return I18nUtil.isChinese() ? bizDictDataDO.getLabelZhCn() : bizDictDataDO.getLabelEnUs();
        }
        return "";
    }

    @Override
    public List<BizDictDataDO> getBizDictTypeProject() {
        return bizDictDataMapper.selectList(BizDictDataDO::getDictTypeId, 5);
    }

    private void validateBizDictDataExists(Long id) {
        if (bizDictDataMapper.selectById(id) == null) {
            throw exception(BIZ_DICT_DATA_NOT_EXISTS);
        }
    }

    private void deleteBizDictDataByDictTypeId(Long dictTypeId) {
        bizDictDataMapper.deleteByDictTypeId(dictTypeId);
    }

	private void deleteBizDictDataByDictTypeIds(List<Long> dictTypeIds) {
        bizDictDataMapper.deleteByDictTypeIds(dictTypeIds);
	}

}